import React from 'react'
import { BaseListPage, IBaseListPageProps, IBaseListPageState, http, uaaApp, UdDrawer, UdModal } from '@/lib'
import apis from '@/apis/SystemMasterDataManage'
import { Select, message, Button, Spin, Switch } from 'antd'
import StateSwitchBtn from '@/components/StateSwitchBtn'
import { downBlobFile } from '@/utils/methods'
import ImportExcelForm from './components/ImportExcelForm'

const Option = Select.Option

const UpdateBtnAuth = 'stock_master_data_product_update'
const MasterProductExport = 'stock_master_data_product_export' //产品主数据导出
const MasterProductImport = 'stock_master_data_product_import' //产品主数据导入

export default class List extends BaseListPage<IProductMasterDataProps, IProductMasterDataState> {
  constructor(props) {
    super(props)
    this.state = {
      title: '产品主数据',
      queryApi: apis.ProductDataList,
      method: 'GET',
      rowKey: 'sapMatCode',
      conditions: [
        { id: 'sapMatCode', label: '物料编码' },
        { id: 'matName', label: '物料描述' },
        {
          id: 'prodSaleLclassIdName',
          label: '产品大类',
          render: () => {
            const {
              classSelectList: { large },
            } = this.state
            return (
              <Select>
                {large.map(({ value, title }) => (
                  <Option key={value} value={title}>
                    {title}
                  </Option>
                ))}
              </Select>
            )
          },
        },
        {
          id: 'prodSaleMclassIdName',
          label: '产品中类',
          render: () => {
            const {
              classSelectList: { middle },
            } = this.state
            return (
              <Select>
                {middle.map(({ value, title }) => (
                  <Option key={value} value={title}>
                    {title}
                  </Option>
                ))}
              </Select>
            )
          },
        },
        {
          id: 'prodSaleSclassIdName',
          label: '产品小类',
          render: () => {
            const {
              classSelectList: { small },
            } = this.state
            return (
              <Select>
                {small.map(({ value, title }) => (
                  <Option key={value} value={title}>
                    {title}
                  </Option>
                ))}
              </Select>
            )
          },
        },
        {
          id: 'isBi',
          label: 'BI',
          render: () => {
            return (
              <Select>
                <Option value={1}>已传</Option>
                <Option value={0}>未传</Option>
              </Select>
            )
          },
        },
        {
          id: 'isValid',
          label: '状态',
          render: () => {
            return (
              <Select>
                <Option value={1}>是</Option>
                <Option value={0}>否</Option>
              </Select>
            )
          },
        },
      ],
      leftBtns: [
        uaaApp.canUse(MasterProductImport) && (
          <Button
            type="primary"
            onClick={() => {
              this.showExcelModal()
            }}
          >
            导入
          </Button>
        ),
        uaaApp.canUse(MasterProductExport) && (
          <Button
            type="primary"
            onClick={() => {
              this.downloadTemplate()
            }}
          >
            导出
          </Button>
        ),
      ],
      columns: [
        ['物料编码', 'sapMatCode'],
        ['物料描述', 'matName'],
        ['包装规格', 'packageSpec'],
        ['产品大类', 'prodSaleLclassIdName'],
        ['产品中类', 'prodSaleMclassIdName'],
        ['产品小类', 'prodSaleSclassIdName'],
        {
          title: 'BI',
          dataIndex: 'isBi',
          render: (text, record, index) => (
            <Switch
              checkedChildren="开"
              unCheckedChildren="关"
              checked={text === 1}
              disabled={!uaaApp.canUse(UpdateBtnAuth)}
              onClick={checked => {
                this.updateBI(record, checked)
              }}
            />
          ),
        },
        {
          title: '状态',
          dataIndex: 'isValid',
          render: (text, record, index) => (
            <Switch
              checkedChildren="开"
              unCheckedChildren="关"
              checked={text === 1}
              disabled={!uaaApp.canUse(UpdateBtnAuth)}
              onClick={checked => {
                this.updateStatus(record, checked)
              }}
            />
          ),
        },
      ],
      classSelectList: {
        large: [],
        middle: [],
        small: [],
      },
      downloading: false,
      uploading: false,
    }
  }
  render() {
    return (
      <Spin
        spinning={this.state.uploading || this.state.downloading}
        tip={this.state.uploading ? '上传中，请稍后...' : '下载中，请稍后...'}
      >
        {super.render()}
      </Spin>
    )
  }
  private downloadTemplate = () => {
    this.setState({ downloading: true })
    http
      .post(apis.downloadBiInfoTemplate, this.queryParams.conditions, { responseType: 'arraybuffer' })
      .then(res => {
        if (!res.data.code) {
          downBlobFile(res.data, '主数据表格')
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }

  private showExcelModal = () => {
    UdModal.open({
      title: '导入文件',
      maskClosable: false,
      content: <ImportExcelForm />,
      okText: '确定',
      cancelText: '取消',
      onOk: values => {
        let { file: fileList } = values
        return this.importExcel(fileList?.[0]?.originFileObj)
      },
    })
  }

  private importExcel = excelFile => {
    const formData = new FormData()
    formData.append('file', excelFile)
    return http.post(apis.importBIExcel, formData, { timeout: 1000 * 60 * 10 }).then(() => {
      message.success('操作成功')
      this.query()
    })
  }

  public componentDidMount() {
    super.componentDidMount()
    this.getFilterSelectList()
  }

  public getFilterSelectList = () => {
    http.get(apis.ProductSelectList).then(res => {
      const { prodSaleLclassIdName = [], prodSaleMclassIdName = [], prodSaleSclassIdName = [] } = res.data
      const large = prodSaleLclassIdName
        .filter(item => item.code)
        .map(({ code: value, name: title }) => ({ value, title }))
      const middle = prodSaleMclassIdName
        .filter(item => item.code)
        .map(({ code: value, name: title }) => ({ value, title }))
      const small = prodSaleSclassIdName
        .filter(item => item.code)
        .map(({ code: value, name: title }) => ({ value, title }))
      const classSelectList: IProductFilterSelect = { large, middle, small }
      this.setState({
        classSelectList,
      })
    })
  }

  public updateBI = (record, checked) => {
    const isBi = checked ? 1 : 0
    const params = { isBi, sapMatCode: record.sapMatCode }
    http.put(apis.updateBiStatus, params).then(res => {
      message.success('操作成功')
      this.query()
    })
  }

  public updateStatus = (record, checked) => {
    const isValid = checked ? 1 : 0
    const params = { isValid, sapMatCode: record.sapMatCode }
    http.put(apis.Update, params).then(res => {
      message.success('操作成功')
      this.query()
    })
  }
}

interface IProductMasterDataProps extends IBaseListPageProps {}

interface IProductMasterDataState extends IBaseListPageState {
  classSelectList: IProductFilterSelect
  downloading?: boolean
  uploading?: boolean
}

interface IProductFilterSelect {
  large: { value: string; title: string }[]
  middle: { value: string; title: string }[]
  small: { value: string; title: string }[]
}
